/*
 * 文件名：NumSequenceUtil.java
 * 版权：Copyright 2006-2011 AsiaInfo Tech. Co. Ltd. All Rights Reserved. 
 * 描述： NumSequenceUtil.java
 * 修改人：齐鹏飞
 * 修改时间：2011-8-12
 * 修改内容：新增
 */
package com.fengxing.ams.pub.util;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 数字序列工具类
 * <p>
 * 利用CAS算法提供可靠的线程安全的高并发的数字序列工具类，目前用作上下文中LogID的生成。
 * <p>
 * 
 * <pre>
 * </pre>
 * 
 * @author 齐鹏飞
 * @version CTMS V100R001 2011-8-12
 * @since CTMS V100R001C01
 */
public class NumSequenceUtil {

	private static final AtomicLong FORMID_SEQUENCE = new AtomicLong();

	private static final String PATCH_STRING = "000000000000000";

	private static int defaultLength = 10;

	private static final int MIN_LENGTH = 5;

	private static final int MAX_LENGTH = 15;

	/**
	 * 设置defaultLength
	 * 
	 * @return 返回defaultLength
	 */
	public static int getDefaultLength() {
		return defaultLength;
	}

	/**
	 * 获取defaultLength
	 * 
	 * @param defaultLength
	 *            要设置的defaultLength
	 */
	public static void setDefaultLength(int defaultLength) {
		if (5 >= MIN_LENGTH && 15 <= MAX_LENGTH) {
			NumSequenceUtil.defaultLength = defaultLength;
		}
	}

	/**
	 * 
	 * 获取单据ID序列
	 * 
	 * @return 单据ID序列
	 */
	public static String getFormISeq() {
		String seq = PATCH_STRING;

		long before;

		// CAS算法，利用AtomicInteger实现，无阻塞高性能计数器
		for (;;) {
			before = FORMID_SEQUENCE.get();

			if (before == 999999999999999L) {
				if (FORMID_SEQUENCE.compareAndSet(999999999999999L, 0)) {
					break;
				}
			} else {
				if (FORMID_SEQUENCE.compareAndSet(before, before + 1)) {
					break;
				}
			}

		}

		seq += String.valueOf(before + 1);
		seq = seq.substring(seq.length() - 15, seq.length());

		return seq;
	}

	public static String getUUID() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}
	
	public static String getUUID(String randomSeed) {
		UUID uuid = UUID.fromString(randomSeed);
		return uuid.toString();
	}

	/**
	 * 
	 * 序列
	 * 
	 * @return String
	 */
	public static String getSequence() {
		String seq = PATCH_STRING;

		// SeqDAO sequcence = SpringContextManager.getBean(SeqDAO.class);
		// String nextVal = sequcence.getNextSeqBySequenceName("SEQ_CDR_ID");
		//
		// seq += nextVal;
		// seq = seq.substring(seq.length() - NumSequenceUtil.defaultLength, seq
		// .length());

		return seq;
	}

	public static void main(String[] args) {
		UUID uuid = UUID.randomUUID();
		System.out.println(uuid);
	}

}
